package com.xuzimian.globaldemo.thirdplatform.wechat.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.Scanner;

/**
 * @author xzm
 * @description wechat 原生帮助类
 */
public class WechatNativeHelper {

    /**
     * 获取微信登录地址
     *
     * @param appid
     * @param redirect_Url
     * @return
     */
    public static String getWechatLoginUrl(String appid, String redirect_Url) throws UnsupportedEncodingException {
        redirect_Url = URLEncoder.encode(redirect_Url, "UTF-8");
        String urlTemplate = "https://open.weixin.qq.com/connect/qrconnect?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_login&state=xzm#wechat_redirect";
        return MessageFormat.format(urlTemplate, appid, redirect_Url);
    }

    /**
     *
     * @param appid
     * @param redirect_Url
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getWechatOauth2AuthorizeUrl(String appid, String redirect_Url) throws UnsupportedEncodingException {
        redirect_Url = URLEncoder.encode(redirect_Url, "UTF-8");
        String urlTemplate = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&state=xzm#wechat_redirect";
        return MessageFormat.format(urlTemplate, appid, redirect_Url);
    }




    /**
     *
     * @param appid
     * @param redirect_Url
     * @return
     * @throws UnsupportedEncodingException
     * @throws URISyntaxException
     */
    public static URI getWechatLoginURI(String appid, String redirect_Url) throws UnsupportedEncodingException, URISyntaxException {
        String url =WechatNativeHelper.getWechatLoginUrl(appid,redirect_Url);
        return new URI(url);
    }


    public static String httpGet(String url) throws IOException {
        HttpClient client = HttpClients.createDefault();//创建HttpClient对象

        HttpGet httpGet = new HttpGet(url);//创建Get请求
        HttpResponse response = client.execute(httpGet);//发送请求，并获取到响应
        Scanner s = new Scanner(response.getEntity().getContent()).useDelimiter("\\A");
        return s.hasNext() ? s.next() : null;//将响应中内容转换为字符串
    }

}
